package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.AlipayPreBean;
import com.ekuaitu.kuaitu.bean.BikePayBean;
import com.ekuaitu.kuaitu.bean.CarPayBean;
import com.ekuaitu.kuaitu.bean.CheckSetupBean;
import com.ekuaitu.kuaitu.bean.PaySuccessEvent;
import com.ekuaitu.kuaitu.bean.SettlementBikeDetailBean;
import com.ekuaitu.kuaitu.bean.SettlementDetailBean;
import com.ekuaitu.kuaitu.bean.WXPreBean;
import com.ekuaitu.kuaitu.payment.AlipayUtils;
import com.ekuaitu.kuaitu.payment.PayResult;
import com.ekuaitu.kuaitu.payment.WXPayUtils;
import com.ekuaitu.kuaitu.utils.BikeInsufficientDepositDialog;
import com.ekuaitu.kuaitu.utils.CarInsufficientDepositDialog;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SetupDialog;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.ToastUtils;
import com.ekuaitu.kuaitu.widget.TextTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jieyaozu on 2017/6/12.
 * 订单结算(包括单车和汽车)
 */

public class SettlementActivity extends BaseActivity {
    @BindView(R.id.confirm_pay)
    TextView tvPay;
    @BindView(R.id.wallet_tv_bike_bzj)
    TextView orderTvCoupon;
    @BindView(R.id.actual_pay_money)
    TextView tvActualPayMoney;//实际支付
    @BindView(R.id.order_pay_money)
    TextTextView ttvOrderPayMoney;//订单费用
    @BindView(R.id.order_yh_money)
    TextTextView ttvYhMoney;//优惠金额
    @BindView(R.id.progressBar_settlement)
    RelativeLayout progressBarSettlement;
    @BindView(R.id.bike_settlement_select_yhq)
    RelativeLayout orderCarCouponRl;
    @BindView(R.id.settlement_haoshi)
    TextTextView ttvHaoshi;//用时
    @BindView(R.id.order_pay_movepay1)
    TextView tvMovePay1;//挪车费用1
    @BindView(R.id.order_pay_movepay2)
    TextView tvMovePay2;//挪车费用1

    private String orderId;
    private String bikeId;
    private String couponId = "0";
    private Context mContext = this;
    private double activityYhPrice = 0;//活动优惠金额
    private double couponPrice = 0;//优惠券金额
    private String coupontitle;
    //实际支付
    private double payMoney;
    //余额
    private double blanceMoney;

    private SettlementDetailBean settlementCarDetail;
    private SettlementBikeDetailBean settlementBikeDetail;
    //最终支付金额
    private double resultMoney;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bike_settlement;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        orderId = getIntent().getStringExtra(IntentKey.INTENT_ORDER_ID);
        Constants.orderId = orderId; //分享页面请求是否还有整备活动
        bikeId = getIntent().getStringExtra(IntentKey.INTENT_BIKE_ID);
        if (TextUtils.isEmpty(bikeId)) {
            SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_TRIP_METHOD, 1); //标记使用的出行方式，下次进入主页面切换出行方式
            getCarSettlementDetail();
        } else {
            SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_TRIP_METHOD, 2);
            getBikeSettlementDetail();
        }
    }

    @OnClick({R.id.confirm_pay, R.id.return_bike_settlement, R.id.bike_settlement_to_detail, R.id.bike_settlement_select_yhq, R.id.call_customer})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_bike_settlement:
                onBackPressed();
                break;
            case R.id.call_customer:
                final KuaituDialog kuaituDialog2 = new KuaituDialog(mContext);
                kuaituDialog2.setTitle(getString(R.string.dialogTitle));
                kuaituDialog2.setMessage("是否拨打客服电话" + MyApplication.getInstance().getHotLine());
                kuaituDialog2.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + MyApplication.getInstance().getHotLine()));
                        startActivity(intent);
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog2.dismiss();
                    }
                });
                kuaituDialog2.show();
                break;
            case R.id.confirm_pay:
                if (TextUtils.isEmpty(bikeId)) {
                    SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.ORDER_TYPE, "1"); //标志订单类型 单车或者汽车
                    carPayOrder();
                } else {
                    SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.ORDER_TYPE, "2");  //标志订单类型 单车或者汽车
                    bikePayOrder();
                }
                break;
            case R.id.bike_settlement_to_detail:
                if (TextUtils.isEmpty(bikeId) && settlementCarDetail != null) {
                    IntentUtils.toCarSettlementDetailActivity(this, orderId, settlementCarDetail, coupontitle, couponPrice);
                } else if (settlementBikeDetail != null) {
                    IntentUtils.toBikeSettlementDetailActivity(this, orderId, bikeId, settlementBikeDetail, coupontitle, couponPrice);
                }
                break;
            case R.id.bike_settlement_select_yhq:
                Intent intent = new Intent(mContext, ChooseCouponActivity.class);
                intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                if (TextUtils.isEmpty(bikeId)) {
                    intent.putExtra(IntentKey.INTENT_TRIP_MODE, "1");
                } else {
                    intent.putExtra(IntentKey.INTENT_TRIP_MODE, "2");
                }
                startActivityForResult(intent, Constants.REQUEST_CHOOSE_COUPON);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == Constants.REQUEST_CHOOSE_COUPON && resultCode == Constants.RESULT_CHOOSE_COUPON) {
            if (intent.getStringExtra("couponId") != null) {
                DecimalFormat df = new DecimalFormat("0.00");
                couponId = intent.getStringExtra("couponId");
                coupontitle = intent.getStringExtra(IntentKey.INTENT_WEBVIEW_TITLE);
                if (couponId.equals("-1")) {
                    couponPrice = 0;
                    orderTvCoupon.setText("未选择优惠券");
                } else {
                    couponPrice = Double.parseDouble(intent.getStringExtra("couponPrice"));
                    orderTvCoupon.setText(df.format(couponPrice) + "元" + coupontitle);
                }
                resultMoney = payMoney - couponPrice;
                if (resultMoney <= 0) {
                    resultMoney = 0;
                }
                tvActualPayMoney.setText(df.format(resultMoney) + "元");
                //Constants.orderPrice = df.format(resultMoney); //邀请好友界面使用结算价格
            }
        }
    }


    /**
     * 单车订单支付
     */
    private void bikePayOrder() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).payBikeOrder(MyApplication.getInstance().getRequestFieldMap(), orderId, couponId).enqueue(new Callback<BikePayBean>() {
            @Override
            public void onResponse(Call<BikePayBean> call, Response<BikePayBean> response) {
                //200-支付完成 401-余额不足 400-提示错误
                progressBarSettlement.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 4);
                        PayResult allPayResult = new PayResult();
                        allPayResult.handlePayResult(SettlementActivity.this, 3,
                                SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.USER_PAY_TYPE),
                                0);
                    } else if (response.body().getStatus() == 401) {
                        final BikeInsufficientDepositDialog depositDialog = new BikeInsufficientDepositDialog(mContext);
                        depositDialog.setYesOnclickListener(null, new BikeInsufficientDepositDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                //立即充值
                                startActivity(new Intent(SettlementActivity.this, ChargeMoneyActivity.class));
                                depositDialog.dismiss();
                            }
                        });
                        DecimalFormat df = new DecimalFormat("0.00");
                        depositDialog.setBalance(df.format(blanceMoney));
                        depositDialog.setPayMoney(df.format(resultMoney));
                        depositDialog.show();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<BikePayBean> call, Throwable t) {
                progressBarSettlement.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 汽车订单支付
     */
    private void carPayOrder() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).payCarOrder(MyApplication.getInstance().getRequestFieldMap(), orderId, couponId).enqueue(new Callback<CarPayBean>() {
            @Override
            public void onResponse(Call<CarPayBean> call, Response<CarPayBean> response) {
                //200-支付完成 401-余额不足,请选择微信支付或充值 400-支付失败,请重试
                progressBarSettlement.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 3);
                        PayResult allPayResult = new PayResult();
                        allPayResult.handlePayResult(SettlementActivity.this, 3,
                                SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.USER_PAY_TYPE),
                                0);
                    } else if (response.body().getStatus() == 401) {
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        final CarInsufficientDepositDialog carInsufficientDepositDialog = new CarInsufficientDepositDialog(mContext);
                        carInsufficientDepositDialog.setWxOnClickListener(new CarInsufficientDepositDialog.WxOnClickListener() {
                            @Override
                            public void onWxClick() {
                                getWxpayParams();
                                carInsufficientDepositDialog.dismiss();
                            }
                        });
                        carInsufficientDepositDialog.setChargeOnClickListener(new CarInsufficientDepositDialog.ChargeOnClickListener() {
                            @Override
                            public void onChargeClick() {
                                //立即充值
                                startActivity(new Intent(SettlementActivity.this, ChargeMoneyActivity.class));
                                carInsufficientDepositDialog.dismiss();
                            }
                        });
                        carInsufficientDepositDialog.setZfbOnClickListener(new CarInsufficientDepositDialog.ZfbOnClickListener() {
                            @Override
                            public void onZfbClick() {
                                getAlipayParams();
                                carInsufficientDepositDialog.dismiss();
                            }
                        });

                        DecimalFormat df = new DecimalFormat("0.00");
                        carInsufficientDepositDialog.setBalance(df.format(blanceMoney));
                        carInsufficientDepositDialog.setPayMoney(df.format(resultMoney));
                        carInsufficientDepositDialog.show();
                    } else {
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CarPayBean> call, Throwable t) {
                progressBarSettlement.setVisibility(View.GONE);
                Toast.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 汽车支付详情
     */
    private void getCarSettlementDetail() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).settlementDetail(MyApplication.getInstance().getRequestFieldMap(), orderId).enqueue(new Callback<SettlementDetailBean>() {
            @Override
            public void onResponse(Call<SettlementDetailBean> call, Response<SettlementDetailBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBarSettlement.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        SettlementDetailBean.AttachmentBean result = response.body().getAttachment();
                        settlementCarDetail = response.body();
                        //耗时
                        int totalMin = result.getModel().getDayMinutes() + result.getModel().getNightMinutes() + result.getModel().getTimeoutMinutes();
                        ttvHaoshi.setValueText(TimeUtils.formatMin(totalMin * 60 + ""));
                        //订单费用
                        DecimalFormat df = new DecimalFormat("0.00");
                        ttvOrderPayMoney.setValueText(df.format(result.getModel().getDayMinutes() * result.getModel().getDayUnitPrice()
                                + result.getModel().getNightMinutes() * result.getModel().getNightUnitPrice() +
                                result.getModel().getTimeoutMoney() + result.getModel().getInsuranceMoney()) + "元");
                        activityYhPrice = response.body().getAttachment().getModel().getTotalSubMoney();
                        //优惠费用
                        ttvYhMoney.setValueText(df.format(response.body().getAttachment().getModel().getTotalSubMoney()) + "元");

                        //余额
                        blanceMoney = result.getModel().getBalance();

                        payMoney = result.getModel().getTotalMoney();
                        resultMoney = payMoney;
                        tvActualPayMoney.setText(df.format(resultMoney) + "元");
                        Constants.orderPrice = df.format(payMoney); //邀请好友界面使用结算价格
                        //orderCarTvJituanMoney.setText("集团账户（" + df.format(result.getModel().getEnterpriseBalance()) + "元)");
                        //orderCarTvGerenMoney.setText("个人账户（" + df.format(result.getModel().getBalance()) + "元)");

                        //能不能使用优惠券
                        int couponPay = response.body().getAttachment().getModel().getCouponPay();
                        if (couponPay == 0) {
                            orderCarCouponRl.setVisibility(View.VISIBLE);
                            orderCarCouponRl.setClickable(false);
                            orderTvCoupon.setText(response.body().getAttachment().getModel().getCouponForbidReason());
                        } else if (response.body().getAttachment().getModel().getCouponPay() == 1) {
                            //没有优惠券，隐藏优惠券框
                            if (response.body().getAttachment().getCoupons() == null || response.body().getAttachment().getCoupons().size() == 0) {
                                orderCarCouponRl.setVisibility(View.GONE);
                            } else {
                                orderCarCouponRl.setVisibility(View.VISIBLE);
                            }
                        }
                    } else {
                        progressBarSettlement.setVisibility(View.GONE);
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarSettlement.setVisibility(View.GONE);
                    Toast.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<SettlementDetailBean> call, Throwable t) {
                progressBarSettlement.setVisibility(View.GONE);
                Log.i("TAG", t.getMessage());
                Toast.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 单车支付详情
     */
    private void getBikeSettlementDetail() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).settlementBikeDetail(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId).enqueue(new Callback<SettlementBikeDetailBean>() {
            @Override
            public void onResponse(Call<SettlementBikeDetailBean> call, Response<SettlementBikeDetailBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBarSettlement.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        SettlementBikeDetailBean.AttachmentBean result = response.body().getAttachment();
                        settlementBikeDetail = response.body();
                        //耗时
                        ttvHaoshi.setValueText(TimeUtils.formatMin(result.getModel().getMinute() * 60 + ""));
                        DecimalFormat df = new DecimalFormat("0.00");
                        tvActualPayMoney.setText(df.format(result.getModel().getRealPrice()) + "元");
                        ttvOrderPayMoney.setValueText(df.format(result.getModel().getOrderPrice()) + "元");
                        //orderBikeXcmoney.setText(df.format(result.getModel().getOrderPrice()) + "元");

                        blanceMoney = result.getModel().getBalance();
                        payMoney = result.getModel().getRealPrice();
                        resultMoney = payMoney;
                        //是否有挪车费用
                        String violationmoney = response.body().getAttachment().getModel().getViolationmoney();
                        boolean isViolation = false;
                        if (!TextUtils.isEmpty(violationmoney)) {
                            isViolation = Integer.parseInt(violationmoney) > 0;
                        }
                        if (isViolation) {
                            tvMovePay1.setVisibility(View.VISIBLE);
                            tvMovePay2.setVisibility(View.VISIBLE);
                            float money = ((float) Integer.parseInt(violationmoney)) / 100;
                            tvMovePay1.setText("(含挪车费" + money + "元)");
                            tvMovePay2.setText("由于您将车辆停放在地图围栏区域外，此单包含围栏外还车需支付的" + money + "元挪车费用。(挪车费用不可用优惠卡支付)");
                        } else {
                            tvMovePay1.setVisibility(View.GONE);
                            tvMovePay2.setVisibility(View.GONE);
                        }
                        //优惠费用
                        double totalYh = 0;
                        for (int i = 0; i < response.body().getAttachment().getModel().getSpecialModelList().size(); i++) {
                            totalYh = totalYh + response.body().getAttachment().getModel().getSpecialModelList().get(i).getSubMoney();
                        }
                        activityYhPrice = totalYh;
                        ttvYhMoney.setValueText(df.format(totalYh) + "元");
                        //能不能使用优惠券
                        int couponPay = response.body().getAttachment().getModel().getCouponPay();
                        if (response.body().getAttachment().getModel().getCouponPay() == 0) {
                            orderCarCouponRl.setVisibility(View.VISIBLE);
                            orderCarCouponRl.setClickable(false);
                            orderTvCoupon.setText(response.body().getAttachment().getModel().getCouponForbidReason());
                        } else if (response.body().getAttachment().getModel().getCouponPay() == 1) {
                            //没有优惠券，隐藏优惠券框
                            if (response.body().getAttachment().getModel().getCoupons() == null || response.body().getAttachment().getModel().getCoupons().size() == 0) {
                                orderCarCouponRl.setVisibility(View.GONE);
                            } else {
                                orderCarCouponRl.setVisibility(View.VISIBLE);
                            }
                            //orderBikeTvCoupon.setText(couponNum + "张可用");
                        }

                    } else {
                        progressBarSettlement.setVisibility(View.GONE);
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBarSettlement.setVisibility(View.GONE);
                    Toast.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<SettlementBikeDetailBean> call, Throwable t) {
                Log.i("TAG", t.getMessage());
                progressBarSettlement.setVisibility(View.GONE);
                Toast.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    //微信支付
    private void getWxpayParams() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatPre(MyApplication.getInstance().getRequestFieldMap(), couponId, orderId, "2").enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 3);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBarSettlement.setVisibility(View.GONE);
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBarSettlement.setVisibility(View.GONE);
                    Toast.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBarSettlement.setVisibility(View.GONE);
                Toast.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //支付宝支付
    private void getAlipayParams() {
        progressBarSettlement.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayPre(MyApplication.getInstance().getRequestFieldMap(), couponId, orderId, "1").enqueue(new Callback<AlipayPreBean>() {
            @Override
            public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 3);
                        String orderInfo = response.body().getAttachment().getStr();
                        AlipayUtils alipayUtils = new AlipayUtils(SettlementActivity.this);
                        alipayUtils.aliPay(orderInfo);
                    } else {
                        progressBarSettlement.setVisibility(View.GONE);
                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBarSettlement.setVisibility(View.GONE);
                    Toast.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                progressBarSettlement.setVisibility(View.GONE);
                Toast.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onBackPressed() {
        final KuaituDialog kuaituDialog = new KuaituDialog(this);
        kuaituDialog.setTitle(getString(R.string.dialogTitle));
        kuaituDialog.setMessage("您确认暂不支付？");
        kuaituDialog.setYesOnclickListener("继续支付", new KuaituDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                kuaituDialog.dismiss();
            }
        });
        kuaituDialog.setNoOnclickListener("暂不支付", new KuaituDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                SharedPreferencesUtils.getInstance(mContext).putIntValue("unpay", 1);
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                kuaituDialog.dismiss();
            }
        });
        kuaituDialog.show();
    }


    //订单支付后的回调（所有支付方式都回调）
    @Subscribe
    public void onPayResult(PaySuccessEvent event) {
        if (event.isPaySuccess == 0) {
            //支付成功
            if ("1".equals(SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.ORDER_TYPE))) { //在每次进入单汽车结算页面时放入此值，汽车1，单车2
                hasSetupActivity();
            } else {
                intentToInvite();
            }

        } else {
            //支付失败
            progressBarSettlement.setVisibility(View.GONE);
        }
    }

    /**
     * 跳转到分享，有分享活动跳转分享，没有活动回到主页面
     */
    private void intentToInvite() {
        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_SHARE_INVITE) == 1) {
            Intent intent = new Intent(mContext, InviteActivity.class);
            intent.putExtra(IntentKey.SHARE_TYPE, 1);  //1从支付页面跳分享  2个人中心跳分享
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }


    //是否享受车辆整备送优惠券活动
    private void hasSetupActivity() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).checkSetup(MyApplication.getInstance().getRequestFieldMap(), Constants.orderId).enqueue(new Callback<CheckSetupBean>() {
            @Override
            public void onResponse(Call<CheckSetupBean> call, final Response<CheckSetupBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    switch (response.body().getStatus()) {
                        case "200":
                            //享受资格
                            if (!isFinishing()) {
                                final SetupDialog setupDialog = new SetupDialog(mContext);
                                setupDialog.setPrice(Constants.orderPrice);
                                setupDialog.setYesOnclickListener("", new SetupDialog.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        Intent intent = new Intent(mContext, CarSetupActivity.class);
                                        long remainingTime = response.body().getAttachment().getLimitTime() - new Date().getTime();
                                        if (remainingTime < 0) {
                                            remainingTime = 0;
                                        }
                                        intent.putExtra("remainingTime", remainingTime);
                                        intent.putExtra("picId", response.body().getAttachment().getPicId());
                                        startActivity(intent);
                                        setupDialog.dismiss();
                                    }
                                });
                                setupDialog.setNoOnclickListener("", new SetupDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        intentToInvite();
                                        setupDialog.dismiss();
                                    }
                                });
                                setupDialog.setCloseOnclickListener(new SetupDialog.onCloseOnclickListener() {
                                    @Override
                                    public void onCloseClick() {
                                        intentToInvite();
                                        setupDialog.dismiss();
                                    }
                                });
                                setupDialog.show();
                            }
                            break;
                        case "400":
                            intentToInvite();
                            break;
                        default:
                            ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            break;
                    }
                } else {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CheckSetupBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
